package fm.cheyiwang.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.controller.BaseController;
import fm.dto.NeiyiUser;
import fm.dto.SystemUser;
import fm.entity.OrderGood;
import fm.entityEnum.OrderEnum;
import fm.exception.BizException;
import fm.exception.TokenInvalidException;
import fm.web.CurrentRequest;
import fm.web.MediaTypes;
import fm.yichenet.mongo.service.*;
import fm.yichenet.service.OrderService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2018/01/30
 * 店铺订单
 * 修改：统一用户类型，
 * TODO 修正订单service调用userService带来的事务问题
 */
@Controller
@RequestMapping("/shop/order/")
public class ShopOrderController extends BaseController {

    @Autowired
    OrderCheckService orderCheckService;

    @Autowired
    OrderService orderService;

    @Autowired
    GoodMgrService goodMgrService;

    @Autowired
    ExpressService expressService;

    @Autowired
    fm.mongoService.UserService userService;

    @Autowired
    UserAddressService userAddressService;
    @Autowired
    VisitHistoryService visitHistoryService;

    /**
     * 提交订单
     *
     * @param orderGoods
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "commit", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map commitOrder(@RequestBody List<OrderGood> orderGoods) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser user = (NeiyiUser) getCurrentUser();
            Map object = orderCheckService.addOrder(orderGoods, user);

            //添加访问记录
            try {
                Map param = new HashMap();
                param.put("good_id", orderGoods.get(0).getGoodId());
                DBObject good = goodMgrService.getGood(param);


                if (user != null && good != null) {
                    NeiyiUser shopUser = userService.getById(orderGoods.get(0).getShopId());

                    DBObject log = new BasicDBObject();
                    log.put("good_class_id", good.get("good_class_id"));
                    log.put("shop_id", good.get("shop_id"));
                    log.put("bigType", good.get("bigType"));
                    log.put("visit_time", new Date());
                    log.put("user_id", user.getId());
                    if (shopUser != null) {
                        log.put("shop_id", shopUser.getId());
                        if (StringUtils.isNotEmpty(shopUser.getUserAdd().getProvince())) {
                            log.put("province", shopUser.getUserAdd().getProvince());
                        }
                        if (StringUtils.isNotEmpty(user.getUserAdd().getCity())) {
                            log.put("city", shopUser.getUserAdd().getCity());
                        }
                    }
                    visitHistoryService.addVisitLog(log);
                }
            } catch (TokenInvalidException ex) {
            } catch (Exception ex) {
                LOGGER.error("获取用户登陆信息失败:", ex);
            }


            res.put("data", object);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "detail", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map orderDesc(@RequestParam(value = "orderId", required = true) String orderId) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            OrderGood orderGood = orderService.getOrderById(orderId);
            Map data = fillOrderInfo(orderGood);
            res.put("data", data);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "cancel", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map cancelOrder(@RequestParam(value = "orderId", required = true) String orderId) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            SystemUser user = (SystemUser) getCurrentUser();
            orderCheckService.cancelOrder(orderId, user);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map orderList(@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                         @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                         @RequestParam(value = "status", required = false) OrderEnum orderEnum) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            SystemUser user = (SystemUser) getCurrentUser();
            List list = orderCheckService.orderList(pageSize, pageNum, user);
            res.put("data", list);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    private Map<String, Object> fillOrderInfo(OrderGood order) throws InterruptedException {
        Map<String, Object> item = new HashMap<>();
        try {

            item.put("order", order);

            String goodId = order.getGoodId();
            if (StringUtils.isNotEmpty(goodId)) {
                DBObject good = goodMgrService.getGood(new BasicDBObject("good_id", goodId).toMap());
                item.put("good", good);
            }
            String expressId = order.getExpressId();
            if (StringUtils.isNotEmpty(expressId)) {
                DBObject express = expressService.getExpress(expressId);
                item.put("express", express);
            }
            String addressId = order.getAddressId();
            if (StringUtils.isNotEmpty(addressId)) {
                DBObject address = userAddressService.getById(addressId);
                item.put("address", address);
            }
            String shopId = order.getShopId();

            if (shopId != null) {
                NeiyiUser user = userService.getById(shopId);
                HashMap shop = new HashMap();
                shop.put("shopName", user.getName());
                shop.put("shopId", shopId);
                shop.put("loc", user.getLng() + "," + user.getLat());
                shop.put("address", user.getUserAdd().getProvince() + "," + user.getUserAdd().getCity() + "," + user.getUserAdd().getDetailAddress());
                shop.put("headimgurl", user.getUserLogo());
                item.put("shop", shop);
            }

        } catch (Exception e) {
            LOGGER.info("获取商户订单发生错误：", e);
        }

        return item;

    }


    @ResponseBody
    @RequestMapping(value = "complete", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map completeOrder(@RequestParam(value = "orderId", required = true) String orderId) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser user = (NeiyiUser) getCurrentUser();
            orderService.updateUserOrderComplete(user, orderId);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        } catch (Exception ex) {
            LOGGER.error("发生错误", ex);
            this.failed(res, "服务器发生了未知错误，请稍后尝试或者联系管理员解决！");
        }
        return res;
    }
}
